<template>
  <div>
    <!-- 可拖动的悬浮球 -->
    <div
      v-show="!showChatWindow"
      ref="floatingBall"
      class="ai-floating-ball"
      :style="ballStyle"
      @mousedown="startDrag"
      @click="openChat"
    >
      <el-icon :size="32" class="chat-icon">
        <ChatDotRound />
      </el-icon>
      <div v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</div>
    </div>

    <!-- 对话窗口 -->
    <transition name="chat-window">
      <div v-show="showChatWindow" class="ai-chat-window" :style="windowStyle">
        <!-- 标题栏 -->
        <div class="chat-header">
          <div class="header-left">
            <el-icon :size="20" class="header-icon">
              <ChatDotRound />
            </el-icon>
            <span class="header-title">AI智能助手</span>
            <el-tag v-if="isConnected" type="success" size="small">在线</el-tag>
            <el-tag v-else type="info" size="small">离线</el-tag>
          </div>
          <div class="header-actions">
            <el-button
              text
              circle
              size="small"
              @click="minimizeChat"
            >
              <el-icon><Minus /></el-icon>
            </el-button>
            <el-button
              text
              circle
              size="small"
              @click="closeChat"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div ref="messageList" class="chat-messages" @scroll="onScroll">
          <div v-if="messages.length === 0" class="welcome-message">
            <el-icon :size="60" class="welcome-icon">
              <ChatDotRound />
            </el-icon>
            <h3>您好！我是AI智能助手</h3>
            <p>有什么可以帮助您的吗？</p>
          </div>

          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message-item', `message-${message.role}`]"
          >
            <div class="message-avatar">
              <el-avatar v-if="message.role === 'user'" :size="36">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-avatar v-else :size="36" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><ChatDotRound /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div v-if="message.loading" class="message-loading">
                  <span class="dot"></span>
                  <span class="dot"></span>
                  <span class="dot"></span>
                </div>
                <div v-else v-html="formatMessage(message.content)"></div>
              </div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            resize="none"
            placeholder="输入您的问题..."
            @keydown.enter.prevent="handleEnter"
          />
          <div class="input-actions">
            <el-button
              text
              size="small"
              @click="clearMessages"
            >
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
            <el-button
              type="primary"
              size="small"
              :loading="isSending"
              :disabled="!inputMessage.trim()"
              @click="sendMessage"
            >
              <el-icon><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { ChatDotRound, Close, Minus, User, Delete, Promotion } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 悬浮球位置
const ballPosition = reactive({
  x: window.innerWidth - 80,
  y: window.innerHeight - 150
});

// 拖拽状态
const isDragging = ref(false);
const dragStart = reactive({ x: 0, y: 0 });

// 聊天窗口状态
const showChatWindow = ref(false);
const isConnected = ref(true);
const unreadCount = ref(0);

// 消息列表
const messages = ref([]);
const inputMessage = ref('');
const isSending = ref(false);

// 引用
const floatingBall = ref(null);
const messageList = ref(null);

// 悬浮球样式
const ballStyle = computed(() => ({
  left: `${ballPosition.x}px`,
  top: `${ballPosition.y}px`
}));

// 窗口样式
const windowStyle = computed(() => ({
  right: '20px',
  bottom: '20px'
}));

// 开始拖拽
const startDrag = (e) => {
  isDragging.value = true;
  dragStart.x = e.clientX - ballPosition.x;
  dragStart.y = e.clientY - ballPosition.y;

  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  
  e.preventDefault();
};

// 拖拽中
const onDrag = (e) => {
  if (!isDragging.value) return;

  let newX = e.clientX - dragStart.x;
  let newY = e.clientY - dragStart.y;

  // 边界限制
  const maxX = window.innerWidth - 70;
  const maxY = window.innerHeight - 70;

  newX = Math.max(0, Math.min(newX, maxX));
  newY = Math.max(0, Math.min(newY, maxY));

  ballPosition.x = newX;
  ballPosition.y = newY;
};

// 停止拖拽
const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

// 打开聊天窗口
const openChat = () => {
  if (isDragging.value) return;
  showChatWindow.value = true;
  unreadCount.value = 0;
  nextTick(() => {
    scrollToBottom();
  });
};

// 最小化聊天窗口
const minimizeChat = () => {
  showChatWindow.value = false;
};

// 关闭聊天窗口
const closeChat = () => {
  showChatWindow.value = false;
};

// 格式化消息内容
const formatMessage = (content) => {
  if (!content) return '';
  // 简单的markdown转换
  return content
    .replace(/\n/g, '<br/>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>');
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isSending.value) return;

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    time: getCurrentTime()
  });

  inputMessage.value = '';
  isSending.value = true;

  // 添加AI加载消息
  const aiMessageIndex = messages.value.length;
  messages.value.push({
    role: 'assistant',
    content: '',
    loading: true,
    time: getCurrentTime()
  });

  scrollToBottom();

  try {
    // 调用后端API
    const response = await fetch('/api/AIChat/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message
      })
    });

    if (!response.ok) {
      throw new Error('网络请求失败');
    }

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let aiContent = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (!line.trim() || !line.startsWith('data:')) continue;

        const data = line.substring(5).trim();
        if (data === '[DONE]') {
          messages.value[aiMessageIndex].loading = false;
          break;
        }

        try {
          const json = JSON.parse(data);
          if (json.choices && json.choices[0]?.delta?.content) {
            aiContent += json.choices[0].delta.content;
            messages.value[aiMessageIndex].content = aiContent;
            messages.value[aiMessageIndex].loading = false;
            scrollToBottom();
          }
        } catch (e) {
          // 忽略JSON解析错误
        }
      }
    }

    if (!aiContent) {
      messages.value[aiMessageIndex].content = '抱歉，我没有收到有效的响应。';
      messages.value[aiMessageIndex].loading = false;
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    messages.value[aiMessageIndex].content = '抱歉，发送消息时出现错误。请稍后再试。';
    messages.value[aiMessageIndex].loading = false;
    ElMessage.error('发送消息失败: ' + error.message);
  } finally {
    isSending.value = false;
    scrollToBottom();
  }
};

// 处理回车键
const handleEnter = (e) => {
  if (e.shiftKey) {
    // Shift+Enter 换行
    return;
  }
  // Enter 发送
  sendMessage();
};

// 清空消息
const clearMessages = () => {
  messages.value = [];
  ElMessage.success('消息已清空');
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  });
};

// 滚动事件
const onScroll = () => {
  // 可以添加滚动到顶部加载历史消息的逻辑
};

// 窗口大小改变
const onResize = () => {
  const maxX = window.innerWidth - 70;
  const maxY = window.innerHeight - 70;
  
  if (ballPosition.x > maxX) ballPosition.x = maxX;
  if (ballPosition.y > maxY) ballPosition.y = maxY;
};

// 组件挂载
onMounted(() => {
  window.addEventListener('resize', onResize);
  
  // 添加欢迎消息
  setTimeout(() => {
    if (messages.value.length === 0) {
      messages.value.push({
        role: 'assistant',
        content: '您好！我是AI智能助手，有什么可以帮助您的吗？',
        time: getCurrentTime()
      });
    }
  }, 500);
});

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', onResize);
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
});
</script>

<style scoped lang="less">
// 悬浮球样式
.ai-floating-ball {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  z-index: 9999;
  transition: transform 0.2s, box-shadow 0.2s;
  user-select: none;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 30px rgba(102, 126, 234, 0.6);
  }

  &:active {
    transform: scale(0.95);
  }

  .chat-icon {
    color: white;
    animation: pulse 2s ease-in-out infinite;
  }

  .unread-badge {
    position: absolute;
    top: 0;
    right: 0;
    background: #f56c6c;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
    border: 2px solid white;
  }
}

// 对话窗口样式
.ai-chat-window {
  position: fixed;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 9998;
  overflow: hidden;

  // 标题栏
  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      .header-icon {
        color: white;
      }

      .header-title {
        font-size: 16px;
        font-weight: 600;
      }
    }

    .header-actions {
      display: flex;
      gap: 5px;

      .el-button {
        color: white;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }

  // 消息列表
  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f5f7fa;

    .welcome-message {
      text-align: center;
      padding: 60px 20px;
      color: #909399;

      .welcome-icon {
        color: #667eea;
        margin-bottom: 20px;
      }

      h3 {
        font-size: 20px;
        color: #303133;
        margin: 0 0 10px 0;
      }

      p {
        font-size: 14px;
        margin: 0;
      }
    }

    .message-item {
      display: flex;
      margin-bottom: 20px;
      animation: messageSlideIn 0.3s ease-out;

      &.message-user {
        flex-direction: row-reverse;

        .message-content {
          align-items: flex-end;

          .message-bubble {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }
        }
      }

      &.message-assistant {
        .message-bubble {
          background: white;
          color: #303133;
        }
      }

      .message-avatar {
        margin: 0 12px;
      }

      .message-content {
        display: flex;
        flex-direction: column;
        max-width: 70%;

        .message-bubble {
          padding: 12px 16px;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          word-wrap: break-word;
          line-height: 1.6;
          font-size: 14px;

          .message-loading {
            display: flex;
            gap: 6px;
            padding: 8px 0;

            .dot {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              background: #909399;
              animation: dotBounce 1.4s infinite ease-in-out both;

              &:nth-child(1) {
                animation-delay: -0.32s;
              }

              &:nth-child(2) {
                animation-delay: -0.16s;
              }
            }
          }
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          margin-top: 6px;
          padding: 0 4px;
        }
      }
    }
  }

  // 输入框
  .chat-input {
    padding: 16px 20px;
    background: white;
    border-top: 1px solid #ebeef5;

    .el-textarea {
      margin-bottom: 10px;
    }

    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

// 动画
.chat-window-enter-active,
.chat-window-leave-active {
  transition: all 0.3s ease;
}

.chat-window-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.9);
}

.chat-window-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.9);
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dotBounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

// 滚动条样式
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;

  &:hover {
    background: #909399;
  }
}
</style>

